package com.elminster.common.db.analyze;

import java.util.ArrayList;
import java.util.List;

abstract public class BaseSqlAnalyzer implements ISqlAnalyzer {

	protected String analyzedSql;
	protected List<Object> analyzedSqlParameters = new ArrayList<Object>();
	
	public BaseSqlAnalyzer() {}
	
	/**
	 * Get the analyzed SQL statement.
	 * @return the analyzed SQL statement
	 */
	@Override
	public String getAnalyzedSql() {
		return analyzedSql;
	}

	/**
	 * Get the analyzed SQL statement's parameter(s).
	 * @return the analyzed SQL statement's parameter(s)
	 */
	@Override
	public List<Object> getAnalyzedSqlParameters() {
		return analyzedSqlParameters;
	}

	/**
	 * Get SQL statement type.
	 * @return SQL statement type
	 */
	@Override
	public SqlType getSqlType() {
		SqlType type = null;
		if (null != analyzedSql) {
			boolean first = false;
			StringBuilder builder = new StringBuilder(15);
			for (int i = 0; i < analyzedSql.length(); i++) {
				char ch = analyzedSql.charAt(i);
				if (Character.isLetter(ch)) {
					if (!first) {
						first = true;
					}
					builder.append(ch);
				} else {
					if (!first) {
						continue;
					} else {
						break;
					}
				}
			}
			if ("select".equalsIgnoreCase(builder.toString())) {
				type = SqlType.QUERY;
			} else if ("call".equals(builder.toString())) {
				type = SqlType.STORED_PROCEDURE;
			} else {
				type = SqlType.UPDATE;
			}
		}
		return type;
	}
}
